package com.lianzhihui.romeex.ui.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.lianzhihui.romeex.R;
import com.lianzhihui.romeex.config.MessageEvent;
import com.lianzhihui.romeex.inter.DialogListener;
import com.lianzhihui.romeex.utils.MyToast;
import com.lianzhihui.romeex.utils.NetUtil;
import com.lianzhihui.romeex.widget.LoadingDialog;
import com.lianzhihui.romeex.widget.dialog.PasswordDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment extends Fragment {

    protected String TAG = this.getClass().getSimpleName();
    protected View rootView;
    Unbinder unbinder;
    //是否第一次可见
    private boolean isFirstVisible = true;
    //是否已加载布局
    protected boolean isViewInitiated;

    protected RxPermissions rxPermissions;
    private long lastCallTime;
    public boolean isVisible;
    public boolean isHidden;
    protected int pageNum = 1;
    //这里用来判断重复频繁点击问题
    protected boolean clickable = true;
    private LoadingDialog loadingDialog;
    protected Activity activity;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        rxPermissions = new RxPermissions(this); //
        activity = getActivity();
        if (rootView == null) {
            rootView = inflater.inflate(getLayoutId(), null);
            unbinder = ButterKnife.bind(this, rootView);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    public void showFullScreen() {
        Window window = activity.getWindow();
        View decorView = window.getDecorView();
        int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        decorView.setSystemUiVisibility(option);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    @NotNull
    public String getStringValues(int resId) {
        return getResources().getString(resId);
    }

    public View getEmptyView() {
        View emptyView = getLayoutInflater().inflate(R.layout.empty_view, null);
        emptyView.findViewById(R.id.emptyRoot).setVisibility(View.VISIBLE);
        return emptyView;
    }

    public void copyString(String string) {
        ClipboardManager cm = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setText(string);
        MyToast.showToast(getResources().getString(R.string.toast_copy_success));
    }

    public void setTextUnderLine(TextView targetView) {
        targetView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        targetView.getPaint().setAntiAlias(true);//抗锯齿
    }


    protected abstract int getLayoutId();

    protected abstract void initView();

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {/* Do something */}

    /**
     * 在fragment首次可见时回调，可在这里进行加载数据，保证只在第一次打开Fragment时才会加载数据，
     * 这样就可以防止每次进入都重复加载数据
     */
    protected void onFragmentFirstVisible() {
    }

    /**
     * fragment 每次可见回调
     */
    protected void onFragmentVisible() {
    }

    /**
     * fragment每次不可见回调
     */
    protected void onFragmentUnVisible() {
    }

    protected void onFragmentVisible(boolean isVisible) {
    }

    @Override
    public void onResume() {
        super.onResume();
        isVisible = isVisible();
        onFragmentVisible(isVisible);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (rootView == null) {
            return;
        }
        if (isVisibleToUser) {
            onFragmentVisible();
            if (isFirstVisible) {
                onFragmentFirstVisible();
                isFirstVisible = false;
            }
        } else {
            onFragmentUnVisible();
        }
        callOnVisibleChange(isVisibleToUser);
    }

    /**
     * 解决重复调用多次问题
     *
     * @param isVisible
     */
    public void callOnVisibleChange(boolean isVisible) {
        long time = System.currentTimeMillis() - lastCallTime;

        if (this.isVisible == isVisible && time < 100) {
            return;
        }
        lastCallTime = System.currentTimeMillis();
        this.isVisible = isVisible;
        onVisibleChange(isVisible);
    }

    public void onVisibleChange(boolean isVisible) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public boolean hasNet() {
        int state = NetUtil.getNetWorkState(activity);
        if (state == NetUtil.NETWORK_NONE) {
            MyToast.showToast(getResources().getString(R.string.toast_no_net));
            return false;
        } else {
//            DataManager.syncWalletInfo(getContext(), new CustomCallback() {
//                @Override
//                public void onCompare(Object o) {
//                    safetyVerifyDialog.show();
//                }
//            });
            return true;
        }
    }

    public void showNetTopView(View view) {
        if (hasNet()) {
            view.setVisibility(View.GONE);
        } else {
            view.setVisibility(View.VISIBLE);
        }

    }

    public <T extends View> T findViewById(@IdRes int id) {
        return rootView.findViewById(id);
    }

    protected void finish() {
        if (activity != null) {
            activity.finish();
        }
    }

    /**
     * 权限申请
     */
    @SuppressLint("CheckResult")
    protected void checkPermissions(String permission) {
        rxPermissions.request(permission)
                .subscribe(granted -> {
                    if (granted) {
                        onPermission(permission, true);
                    } else {
                        onPermission(permission, false);
                    }
                });

    }

    protected void showLoading(String title) {
        if (isAdded()) {
            try {
                if (loadingDialog == null) {
                    loadingDialog = new LoadingDialog(activity);
                    loadingDialog.center();
                    loadingDialog.setTitle(title);
                }
                loadingDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        clickable = true;
                    }
                });
                loadingDialog.show();
            } catch (Exception e) {

            }
        }
    }

    protected void dismissLoading() {
        if (isAdded()) {
            if (loadingDialog != null && loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
        }
    }

    /**
     * 权限申请结果
     *
     * @param permisstion 权限名称
     * @param isGranted   权限结果
     */
    protected void onPermission(String permisstion, boolean isGranted) {

    }

    // 成员变量mToast
    private Toast mToast;

    /**
     * 显示 toast,在可是界面中优先使用该方法
     *
     * @param content
     */
    @SuppressLint("ShowToast")
    protected void toast(String content) {
        // 显示Toast
        if (mToast == null) {
            if (activity != null) {
                mToast = Toast.makeText(activity, content, Toast.LENGTH_SHORT);
            }
        } else {
            mToast.setText(content);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    /**
     * 显示 toast,在可是界面中优先使用该方法
     *
     * @param content
     */
    @SuppressLint("ShowToast")
    protected void toast(String content, int gravity) {
        // 显示Toast
        if (mToast == null) {
            if (activity != null) {
                mToast = Toast.makeText(activity, content, Toast.LENGTH_SHORT);
                mToast.setGravity(gravity, 0, 0);
            }
        } else {
            mToast.setText(content);
            mToast.setGravity(gravity, 0, 0);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    protected void showSafty(DialogListener listener) {
        PasswordDialog dialog = new PasswordDialog(activity, getString(R.string.input_password));
        dialog.setListener(listener);
        dialog.show();
    }

    /**
     * eventbus 发送消息
     *
     * @param event
     * @param obj
     */
    protected void sendMessage(int event, Object obj) {
        EventBus.getDefault().post(new MessageEvent(event, obj));
    }

}

